package com.intel.factorytest.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import com.intel.factorytest.R;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;

public class NFCTest extends BaseActivity {
    private NfcAdapter nfcAdapter;
    private TextView promt;
    private PendingIntent pi;
    private static boolean DEBUG_LOG = true;
    byte a[] = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nfc_test);
        promt = (TextView) findViewById(R.id.promt);
        mSucBtn = (Button) findViewById(R.id.success_button);
        mSucBtn.setVisibility(View.INVISIBLE);
        // 获取默认的NFC控制器
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter != null) {
            nfcAdapter.enable();
        }

        IntentFilter mIntentFilter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
        registerReceiver(mReceiver, mIntentFilter, "permission.CIT_ALLOW_BROADCAST", null);

        super.initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (nfcAdapter != null) {
            nfcAdapter.disable();
            nfcAdapter = null;
        }
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //得到是否检测到ACTION_TECH_DISCOVERED触发
        intentH = getIntent();
        if(pi ==null){
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        }
        if (nfcAdapter == null) {
            promt.setText("设备不支持NFC！");
            // finish();
            return;
        }
        if (!nfcAdapter.isEnabled()) {
            promt.setText("请在系统设置中先启用NFC功能！");
            // finish();
            return;
        }
        nfcAdapter.enableForegroundDispatch(this, pi, null, null);
        if(DEBUG_LOG){
            android.util.Log.i("NFCTest", "Resume intent action is "+getIntent().getAction());
        }
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()) ||
            NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction()) ||
            NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
            //处理该intent
            processIntent(getIntent());
        } else {
            promt.setText(R.string.nfc_prompt);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null) {
            nfcAdapter.disableForegroundDispatch(this);
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (NfcAdapter.ACTION_ADAPTER_STATE_CHANGED.equals(action)) {
                int newState = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE, NfcAdapter.STATE_OFF);
                switch (newState) {
                    case NfcAdapter.STATE_OFF:
                        promt.setText("设备NFC已关闭！");
                        break;
                    case NfcAdapter.STATE_ON:
                        promt.setText("设备NFC已打开！");
                        break;
                    case NfcAdapter.STATE_TURNING_ON:
                        promt.setText("正在打开设备NFC！");
                        break;
                    case NfcAdapter.STATE_TURNING_OFF:
                        promt.setText("正在关闭设备NFC！");
                        break;
                }
                NFCTest.this.onResume();
            }
        }
    };

    private Intent intentH = null;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        setIntent(intent);
        intentH = intent;
        if(DEBUG_LOG) {
            android.util.Log.i("NFCTest", "nfc test is begining !" + "intent = " +intent);
        }
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
            NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction()) ||
            NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(intent);
        } else {
            Toast.makeText(NFCTest.this, "newIntent", Toast.LENGTH_SHORT).show();
        }
    }

    public static String ByteArrayToHexString(byte[] bytesId) {   //Byte数组转换为16进制字符串
        // TODO 自动生成的方法存根
        int i, j, in;
        String[] hex = {
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        String output = "";
        for (j = 0; j < bytesId.length; ++j) {
            in = bytesId[j] & 0xff;
            i = (in >> 4) & 0x0f;
            output += hex[i];
            i = in & 0x0f;
            output += hex[i];
        }
        return output;
    }

    //字符序列转换为16进制字符串
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("0x");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    private void processIntent(Intent intent) {
        if(DEBUG_LOG) {
            android.util.Log.i("NFCTest", "intent is received !");
        }
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String tag = getResources().getString(R.string.nfc_tag) + tagFromIntent.toString();
        promt.setText(tag);
        makeFile();
        //this.finish();
        mSucBtn.setVisibility(View.VISIBLE);
    }

    private void makeFile() {
        File mFile = new File("/mnt/sdcard/nfc.txt");
        //判断文件是否存在
        if (mFile.exists()) {
            mFile.delete();
            //return;
        }
        String strContent = "pass";
        try {
            //创建文件
            mFile.createNewFile();
            RandomAccessFile raf = new RandomAccessFile(mFile, "rwd");
            raf.seek(mFile.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}